﻿using Common.Framework.Core.Common;
using Common.Framework.Core.Extension;
using Common.Framework.Core.Serilog;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Serilog;
using Serilog.Events;
using Snowflake.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Framework.Core.Attribute
{
    /// <summary>
    /// 操作
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class OperationAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 方法名称
        /// </summary>
        private string ActionName { get; set; }
        /// <summary>
        /// 控制器别名
        /// </summary>
        private string ControlleAlias { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ControlleAlias"></param>
        /// <param name="ActionName"></param>
        public OperationAttribute(string ControlleAlias, string ActionName)
        {
            this.ControlleAlias = ControlleAlias;
            this.ActionName = ActionName;
        }
        /// <summary>
        /// 控制器中的操作执行之前调用此方法
        /// </summary>
        /// <param name="context"></param>
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var controllerName = (string)context.RouteData.Values["controller"];
            var actionName = (string)context.RouteData.Values["action"];
            var httpContext = context.HttpContext;
            var request = httpContext.Request;
            request.Body.Position = 0;
            StreamReader sr = new StreamReader(request.Body);
            string body = await sr.ReadToEndAsync();
            request.Body.Position = 0;
            LogEntityRequest entity = new LogEntityRequest();
            entity.Message = body;
            entity.LogObjTypeAlias = this.ControlleAlias;
            entity.Level = LogEventLevel.Information;
            entity.LogObjType = controllerName;
            entity.OperationName = this.ActionName;
            entity.OperationType = actionName;
            entity.Request = request;
            LoggerHelper.Information(entity);
            await next();
        }

        /// <summary>
        /// 控制器中的操作执行之后调用此方法
        /// </summary>
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            // Method intentionally left empty.
        }
    }
}
